﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Web.Mvc;
using System.Web.WebPages.Html;

namespace Matrix.Common.Utility
{
    /// <summary>
    /// EnumUtil
    /// </summary>
    public static class EnumUtil
    {
        private static readonly Hashtable htCache = Hashtable.Synchronized(new Hashtable());

        public static int GetValue(this System.Enum obj)
        {
            return obj.GetHashCode();
        }

        /// <summary>
        /// 获取枚举对应的Description内容
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static IList<KeyValuePair<string, string>> GetEnumDescriptions(Type type)
        {
            if (htCache.Contains(type))
                return htCache[type] as IList<KeyValuePair<string, string>>;
            IList<KeyValuePair<string, string>> dict = GetDictionary(type);
            htCache[type] = dict;
            return dict;
        }

        private static IList<KeyValuePair<string, string>> GetDictionary(Type type)
        {
            FieldInfo[] fields = type.GetFields();
            IList<KeyValuePair<string, string>> dict = new List<KeyValuePair<string, string>>();
            for (int i = 1; i < fields.Length; i++)
            {
                FieldInfo item = fields[i];
                string desription;
                object[] objs = item.GetCustomAttributes(typeof(DescriptionAttribute), false);
                if (objs != null && objs.Length != 0)
                {
                    DescriptionAttribute da = (DescriptionAttribute)objs[0];
                    desription = da.Description;
                }
                else
                {
                    desription = item.Name;
                }
                dict.Add(new KeyValuePair<string, string>(((int)Enum.Parse(type, item.Name)).ToString(), desription));
            }
            return dict;
        }

        /// <summary>
        /// 对于标记为Flags的枚举，判断枚举值A是否包含在枚举值B中
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="optionA"></param>
        /// <param name="optionB"></param>
        /// <returns></returns>
        public static bool IsInOption<T>(T optionA, T optionB)
        {
            //int i = optionB.GetHashCode() - optionA.GetHashCode();
            //return (i & (i - 1)) == 0;//是否2的乘方
            var options = new List<string>();
            options.AddRange(optionB.ToString().Split(','));
            return options.Contains(optionA.ToString());
        }

        /// <summary>
        /// 对于标记为Flags的枚举值，返回对应的HashCode
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="names"></param>
        /// <returns></returns>
        public static IList<int> GetCodesFromEnumString<T>(string names)
        {
            var codes = new List<int>();
            //int i = 0;
            foreach (string name in names.Split(','))
            {
                T t2 = (T)Enum.Parse(typeof(T), name);
                codes.Add(t2.GetHashCode());
            }
            return codes;
        }

        /// <summary>
        /// 取出枚举的值对应的描述方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetEnumDescrptionByKey<T>(string key)
        {
            var diclist = EnumUtil.GetEnumDescriptions(typeof(T));
            var keyvalueList = diclist.Where(d => d.Key.ToLower().Equals(key.ToLower().Trim()));
            if (keyvalueList.Any())
                return keyvalueList.First().Value;
            return string.Empty;
        }

        /// <summary>
        /// 获取枚举的描述文本
        /// </summary>
        /// <param name="e">枚举成员</param>
        /// <returns></returns>
        public static string GetEnumDescription(object e)
        {
            //获取字段信息
            System.Reflection.FieldInfo[] ms = e.GetType().GetFields();

            Type t = e.GetType();
            foreach (System.Reflection.FieldInfo f in ms)
            {
                //判断名称是否相等
                if (f.Name != e.ToString()) continue;

                //反射出自定义属性
                foreach (Attribute attr in f.GetCustomAttributes(true))
                {
                    //类型转换找到一个Description，用Description作为成员名称
                    System.ComponentModel.DescriptionAttribute dscript = attr as System.ComponentModel.DescriptionAttribute;
                    if (dscript != null)
                        return dscript.Description;
                }

            }
            //如果没有检测到合适的注释，则用默认名称
            return e.ToString();
        }

        ///// <summary>
        /////  把枚举的描述和值绑定到DropDownList
        ///// </summary>
        ///// <param name="enumType"></param>
        ///// <returns></returns>
        //public static List<SelectListItem> GetCategorySelectList(Type enumType)
        //{
        //    List<SelectListItem> selectList = new List<System.Web.Mvc.SelectListItem>();
        //    selectList.Add(new SelectListItem { Text = "--请选择类型--", Value = "-1", Selected = true });

        //    foreach (object e in Enum.GetValues(enumType))
        //    {
        //        selectList.Add(new SelectListItem { Text = GetEnumDescription(e), Value = ((int)e).ToString() });
        //    }

        //    return selectList;
        //}
    }
}
